package com.yoomiito.app.ui.account;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yoomiito.app.act.NewFreeBuyActivity;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;

import com.yoomiito.app.base.WebViewActivity;
import com.yoomiito.app.model.bean.AreaInfo;
import com.yoomiito.app.model.bean.UserInfo;
import com.yoomiito.app.present.account.LoginPresent;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.CheckUtil;
import com.yoomiito.app.utils.ColorUtils;
import com.yoomiito.app.utils.Const;
import com.yoomiito.app.utils.EditTextUtil;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.LoginUtils;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.utils.inputfilter.TelNum334Filter;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.wx.WXUtils;
import com.yoomiito.app.widget.SelectView;
import com.yoomiito.app.widget.dialog.AreaDialog;
import com.yoomiito.app.widget.dialog.FreeBuyDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.router.Router;


/**
 * 1.手机号码正常登陆
 * <p>
 * 2、微信登陆
 *
 */
public class LoginActivity extends BaseActivity<LoginPresent> {

    @BindView(R.id.tv_phone)
    EditText evPhone;

    @BindView(R.id.tv_code)
    EditText evCode;

    @BindView(R.id.send_code)
    TextView sendCode;
    @BindView(R.id.tv_login)
    Button tvLogin;

    @BindView(R.id.tv_weichat)
    TextView tvWeichat;
    @BindView(R.id.tv_protocol)
    TextView tv_protocol;
    @BindView(R.id.iv_delete)
    ImageView iv_delete;
    @BindView(R.id.iv_back_left)
    ImageView backIv;
    @BindView(R.id.checkView)
    SelectView checkView;

    @BindView(R.id.tv_pre)
    TextView tvArea;

    private String area = "86";

    AreaDialog areaDialog;

    private String mPhone;
    private EditTextUtil mEditTextUtil;
    private String mLoginType;

    public static void start(Context context){
        Intent intent = new Intent(context,LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public LoginPresent newP() {
        return new LoginPresent(App.mAppConfig);
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        mEditTextUtil = new EditTextUtil(evPhone, tvLogin);
//        mEditTextUtil.setPhoneType(true);
        mEditTextUtil.setNumberLength(11);
        mEditTextUtil.setIvDelete(iv_delete);
        evPhone.setFilters(new InputFilter[]{new TelNum334Filter().setMaxLength(12)});
//        if (AllCode.ExpLogin==mLoginType){
//        backIv.setVisibility(View.GONE);
//        }
        mEditTextUtil.setEditTextListener1();

    }


    @Override
    protected void onResume() {
        super.onResume();
//        if (AllCode.ExpLogin == mLoginType) {
//            AppManager.getAppManager().finishOtherActivity(LoginActivity.class);
//        }
//        if (!WXUtils.INSTANCE.isInstallWX(this)){
//            tvWeichat.setVisibility(View.GONE);
//        }
    }

    @OnClick({R.id.tv_login,R.id.tv_pre,R.id.send_code, R.id.tv_weichat, R.id.tv_protocol,R.id.privacyAgreementTv, R.id.iv_delete, R.id.tv_guimihui})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.send_code://发送验证码
//                mPhone = evPhone.getText().toString().trim();
                mPhone = mEditTextUtil.getPhoneText();
                if (TextUtils.isEmpty(mPhone)) {
                    getvDelegate().centerToastShort(getString(R.string.input_phone_num));
                    return;
                }
                if (!CheckUtil.isMobileNO(mPhone)) {
                    getvDelegate().centerToastShort(getString(R.string.error_phone_toast));
                    return;
                }
                if (!checkView.isSelected()){
                    YMToast.showCenterToast("请阅读并同意《用户协议》和《隐私政策》");
                    return;
                }
                if (AllUtils.isFastClick()){
                    return;
                }
                showLoading();
                getP().requestSendCode(mPhone,area);
                break;
            case R.id.tv_weichat://微信登陆
                if (!checkView.isSelected()){
                    YMToast.showCenterToast("请阅读并同意《用户协议》和《隐私政策》");
                    return;
                }
                getP().authorization(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.tv_guimihui://
                Router.newIntent(this)
                        .to(GuiMIHuiLoginActivity.class)
                        .launch();
                break;
            case R.id.iv_delete://清空输入框
                evPhone.setText("");
                break;
            case R.id.tv_protocol://用户协议
                Router.newIntent(this)
                        .to(WebViewActivity.class)
                        .putInt(Constant.TYPE, AllCode.UserAgreement)
                        .launch();
                break;
            case R.id.privacyAgreementTv://隐私协议
                Router.newIntent(this)
                        .to(WebViewActivity.class)
                        .putInt(Constant.TYPE, Const.Url.PrivacyAgreement)
                        .launch();
                break;

            case R.id.tv_pre:
                getP().getArea();
                break;
            case R.id.tv_login:
                if (!checkView.isSelected()){
                    YMToast.showCenterToast("请阅读并同意《用户协议》和《隐私政策》");
                    return;
                }
                mPhone = mEditTextUtil.getPhoneText();
                String phoneCode = evCode.getText().toString().trim();
                if (TextUtils.isEmpty(phoneCode)) {
                    getvDelegate().toastShort(getString(R.string.input_check_code_hint));
                    return;
                }
                getP().requestVerifyCode(phoneCode, mPhone, "");
                break;
        }
    }

    private void wxLoginCheckCode(String openId){


    }

    @Override
    public void eventMessage(EventMessage eventMessage) {
        super.eventMessage(eventMessage);
        if (AllCode.LoginSuccess.equals(eventMessage.getEventType())){
            this.finish();
        }
    }

    public void CountdownTimeTask(int time) {
        sendCode.setText(time + getString(R.string.send_code_time_hint));
        sendCode.setEnabled(false);
        sendCode.setBackgroundResource(R.drawable.bg_blue1);
    }

    public void timeEndTask() {
        sendCode.setText("重新发送");
        sendCode.setEnabled(true);
        sendCode.setBackgroundResource(R.drawable.bg_blue);

    }
    /**
     * 去往主界面
     */
    public void toMainActivity(UserInfo userInfo) {
        getP().destroyCountdownTask();
//        App.mAppConfig.mCurrentUser.mUserInfo = userInfo;
//
//        SharedPref.getInstance(App.getInstance()).putBoolean(Constant.IS_LOGIN, true);
//        SharedPref.getInstance(App.getInstance()).putString(Constant.TOKEN, userInfo.getToken());
//        UserInfoConfig.loginPutUserConfig(userInfo,true);
//        Router.newIntent(context)
//                .to(MainActivity.class)
//                .launch();
//        EventMessage em = new EventMessage();
//        em.setEventType(AllCode.LoginSuccess);
//        EventBus.getDefault().post(em);
        LoginUtils.INSTANCE.loginHandle(this,userInfo);
    }

    /**
     * 去往确认验证码
     */
    public void toInputCodeCheckActivity() {
//        Router.newIntent(context)
//                .to(InputCodeCheckActivity.class)
//                .putString("phone", mPhone)
//                .putInt("type", Constant.Phone_Login)
//                .launch();
    }


    /**
     * 微信登陆 --绑定手机号
     */
    public void toBindingPhoneActivity(UserInfo userInfo) {
        getP().destroyCountdownTask();
        finish();
        mEditTextUtil.deleteTextWatcher();
        Router.newIntent(context)
                .to(LoginBindActivity.class)
                .putString("openid",userInfo.openid)
                .putString("nickname",userInfo.getNickname())
                .putString("headimgurl",userInfo.getHeadimgurl())
                .putInt("sex",userInfo.getSex())
                .launch();
    }


    public void getArea(List<AreaInfo> areaInfoList){
        areaDialog = new AreaDialog(context);
        areaDialog.setData(areaInfoList);
        areaDialog.setOnViewClickListener(new AreaDialog.OnClickListener() {
            @Override
            public void onClick(String area1) {
                area = area1;
                tvArea.setText("+"+area1);
                areaDialog.dismiss();
            }
        });
        areaDialog.show();
    }

    public void toBindInviteCode(){
        getP().destroyCountdownTask();
        Router.newIntent(this)
                .to(InvitationCodeActivity.class)
                .launch();
    }
    @Override
    protected void onDestroy() {
        getP().destroyCountdownTask();
//        RxBusManager.unregisterRxBusManager(this);
        mEditTextUtil.deleteTextWatcher();
        super.onDestroy();
        UMShareAPI.get(this).release();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
//        if (AllCode.ExpLogin != mLoginType) {
            super.onBackPressed();
//        }
    }


    public void success(String binding) {
        Router.newIntent(context)
                .to(InvitationCodeActivity.class)
                .putString("phone", mPhone)
                .putString("binding", binding)
                .launch();
    }

    public void toMain(UserInfo userInfo){
        LoginUtils.INSTANCE.loginHandle(this,userInfo);
//        UserInfoConfig.loginPutUserConfig(userInfo,true);
//        EventMessage em = new EventMessage();
//        em.setEventType(AllCode.LoginSuccess);
//        EventBus.getDefault().post(em);
    }
}
